<?php
// 短網址服務
class ShortUrlModel extends Model {
	protected $tableName = 'short_url';
	// 通过短网址还原长网址
	function getLongURL($shortURL) {
		if(empty($shortURL)){
			return ;
		}
		$map ['shortURL'] = t ( $shortURL );
		$longURL = $this->where ( $map )->getField ( 'longURL' );
		
		return $longURL;
	}
	// 通过长网址取得短网址，短网址不存在则自动增加
	function getShortURL($longURL) {
		if(empty($longURL)){
			return ;
		}		
		$map ['longURL'] = t ( $longURL );
		$shortURL = $this->where ( $map )->getField ( 'shortURL' );
		//dump($this->getLastSql());
		//dump($shortURL);
		if (! $shortURL) {
			$shortURL = $this->put ( $longURL );
		}
		
		return $shortURL;
	}
	// 保存短网址
	function put($longURL) {
		$map ['shortURL'] = $this->shorturl ( $longURL );
		$map ['longURL'] = $longURL;
		//dump($map);
		$res = $this->add ( $map );
		return $map ['shortURL'];
	}
	
	// 生成短网址
	function shorturl($input) {
		$base32 = array (
				'a',
				'b',
				'c',
				'd',
				'e',
				'f',
				'g',
				'h',
				'i',
				'j',
				'k',
				'l',
				'm',
				'n',
				'o',
				'p',
				'q',
				'r',
				's',
				't',
				'u',
				'v',
				'w',
				'x',
				'y',
				'z',
				'0',
				'1',
				'2',
				'3',
				'4',
				'5' 
		);
		
		$hex = md5 ( $input );
		$hexLen = strlen ( $hex );
		$subHexLen = $hexLen / 8;
		$output = array ();
		
		for($i = 0; $i < $subHexLen; $i ++) {
			$subHex = substr ( $hex, $i * 8, 8 );
			$int = 0x3FFFFFFF & (1 * ('0x' . $subHex));
			$out = '';
			
			for($j = 0; $j < 6; $j ++) {
				$val = 0x0000001F & $int;
				$out .= $base32 [$val];
				$int = $int >> 5;
			}
			
			$output [] = $out;
		}
		
		return $output[0];
	}
}
